package com.wk.springbootlearn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wk.springbootlearn.mapper.GroupTeamMapper;
import com.wk.springbootlearn.pojo.entity.GroupTeam;
import com.wk.springbootlearn.pojo.entity.Team;
import com.wk.springbootlearn.mapper.TeamMapper;
import com.wk.springbootlearn.pojo.form.GetTeamForm;
import com.wk.springbootlearn.pojo.form.TeamForm;
import com.wk.springbootlearn.service.TeamService;
import lombok.Setter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TeamServiceImpl implements TeamService {

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private GroupTeamMapper groupTeamMapper;

    @Override
    public void createTeam(TeamForm teamForm, Long userId) {
        Team team = new Team();
        BeanUtils.copyProperties(teamForm, team);
        team.setCreator(userId);
        team.setUpdator(userId);
        teamMapper.insert(team);
    }

    @Override
    public void updateTeam(Long id, TeamForm teamForm, Long userId) {
        // 判断当前团队是否存在
        Team team = teamMapper.selectById(id);
        if (team == null) throw new RuntimeException("无效的团队id");
        // 判断当前团队信息是否与数据库信息相同
        if (team.getTeamName().equals(teamForm.getTeamName())) return;
        // 更新信息
        Team team1 = new Team();
        team1.setId(id);
        team1.setTeamName(teamForm.getTeamName());
        team1.setUpdator(userId);
        teamMapper.updateById(team1);
    }

    @Override
    public IPage<Team> findTeam(GetTeamForm getTeamForm) {
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        if (getTeamForm.getTeamName() != null) queryWrapper.eq("team_name", getTeamForm.getTeamName());

        Page<Team> teamPage = new Page<>(getTeamForm.getPage(), getTeamForm.getPageSize());
        return teamMapper.selectPage(teamPage, queryWrapper);
    }

    @Override
    @Transactional
    public void delTeam(Long id) {
        // 判断该团队id是否有效
        Team team = teamMapper.selectById(id);
        if (team == null) throw new RuntimeException("无效的团队id");
        // 删除团队
        teamMapper.deleteById(id);
        // 删除该团队与小组的关系记录
        QueryWrapper<GroupTeam> wrapper = new QueryWrapper<GroupTeam>().eq("team_id", id);
        groupTeamMapper.delete(wrapper);
    }
}
